package com.cdd.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdd.eduservice.entity.EduCourse;
import com.cdd.eduservice.entity.EduCourseDescription;
import com.cdd.eduservice.entity.frontVo.CourseQueryVo;
import com.cdd.eduservice.entity.frontVo.CourseWebVo;
import com.cdd.eduservice.entity.vo.CourseInfoVo;
import com.cdd.eduservice.entity.vo.CoursePublishVo;
import com.cdd.eduservice.mapper.EduCourseMapper;
import com.cdd.eduservice.service.IEduChapterService;
import com.cdd.eduservice.service.IEduCourseDescriptionService;
import com.cdd.eduservice.service.IEduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdd.eduservice.service.IEduVideoService;
import com.cdd.servicebase.handler.SmartException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author cdd
 * @since 2021-02-02
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements IEduCourseService {

    @Autowired
    private IEduCourseDescriptionService eduCourseDescriptionService;

    @Autowired
    private IEduVideoService eduVideoService;

    @Autowired
    private IEduChapterService eduChapterService;

    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        // 将课程数据插入到课程表
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        eduCourse.setGmtCreate(localDateTime);
        eduCourse.setGmtModified(localDateTime);
        int insert = baseMapper.insert(eduCourse);
        if(insert == 0) {
            throw new SmartException(20001, "课程插入失败！");
        }

        String courseId = eduCourse.getId();
        // 将课程数据描述插入到课程简介表
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setDescription(courseInfoVo.getDescription());
        eduCourseDescription.setId(courseId);
        eduCourseDescription.setGmtCreate(localDateTime);
        eduCourseDescription.setGmtModified(localDateTime);
        eduCourseDescriptionService.save(eduCourseDescription);
        return courseId;
    }

    @Override
    public CourseInfoVo getCourseInfo(String courseId) {

        CourseInfoVo courseInfoVo = new CourseInfoVo();
        // 查询course
        EduCourse eduCourse = baseMapper.selectById(courseId);
        BeanUtils.copyProperties(eduCourse, courseInfoVo);
        // 查询description
        EduCourseDescription eduCourseDescription = eduCourseDescriptionService.getById(courseId);
        courseInfoVo.setDescription(eduCourseDescription.getDescription());
        return courseInfoVo;
    }

    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        // 修改课程表
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        eduCourse.setGmtModified(localDateTime);
        int i = baseMapper.updateById(eduCourse);
        if(i == 0) {
            throw new SmartException(20001, "修改课程信息失败！");
        }

        // 修改描述表
        EduCourseDescription description = new EduCourseDescription();
        description.setId(courseInfoVo.getId());
        description.setDescription(courseInfoVo.getDescription());
        description.setGmtModified(localDateTime);
        boolean b = eduCourseDescriptionService.updateById(description);
        if(!b) {
            throw new SmartException(20001, "修改课程描述失败！");
        }
    }

    @Override
    public CoursePublishVo getPublishInfo(String courseId) {
        CoursePublishVo publishInfo = baseMapper.getPublishInfo(courseId);
        return publishInfo;
    }

    @Override
    public void removeCourse(String courseId) {
        // 删除课程小节，由于还要删除对应的视频，所以需要自己实现具体的删除方法
        eduVideoService.removeVideoByCourseId(courseId);
        // 删除课程章节
        eduChapterService.removeChapterByCourseId(courseId);
        // 删除课程描述
        eduCourseDescriptionService.removeById(courseId);
        // 删除课程本身
        int i = baseMapper.deleteById(courseId);
        if(i == 0) {
            throw new SmartException(20001, "课程删除失败");
        }
    }

    @Override
    public List<EduCourse> selectByTeacherId(String id) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("teacher_id", id);
        //按照最后更新时间倒序排列
        queryWrapper.orderByDesc("gmt_modified");

        List<EduCourse> courses = baseMapper.selectList(queryWrapper);
        return courses;
    }

    @Override
    public Map<String, Object> getFrontCourseList(Page<EduCourse> pageParam, CourseQueryVo courseQueryVo) {

        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseQueryVo.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", courseQueryVo.getSubjectParentId());
        }

        if (!StringUtils.isEmpty(courseQueryVo.getSubjectId())) {
            queryWrapper.eq("subject_id", courseQueryVo.getSubjectId());
        }

        if (!StringUtils.isEmpty(courseQueryVo.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(courseQueryVo.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseQueryVo.getPriceSort())) {
            queryWrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageParam, queryWrapper);

        List<EduCourse> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    @Override
    public CourseWebVo selectInfoWebById(String id) {
        this.updatePageViewCount(id);
        return baseMapper.selectInfoWebById(id);
    }

    @Override
    public void updatePageViewCount(String id) {
        EduCourse course = baseMapper.selectById(id);
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);
    }
}
